package com.thti.mecool.client.util;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import com.thti.mecool.client.model.po.TaskManage;
import com.thti.mecool.client.service.Protocol;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 
 * @author weiguo.ren
 * 
 */

public class NetTool {
	private static NetProgress netProgress;
	public static InputStream POST(String url,String params)throws Exception{
		HashMap<String, String> map = new HashMap<String, String>();
		String[] pp=params.split("&");
		for (int i = 0; i < pp.length; i++) {
			String kv=pp[i];
			String[] keyValue=kv.split("=");
			if(keyValue.length>1){
				map.put(keyValue[0], keyValue[1]);
			}else{
				map.put(keyValue[0],"");
			}
		}
		HttpPost request = new HttpPost(url);
		List<NameValuePair> p = new ArrayList<NameValuePair>();
		for (Map.Entry<String, String> entry : map.entrySet()) {
			p.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
		}
		HttpEntity entity = new UrlEncodedFormEntity(p, "UTF-8");
		request.setEntity(entity);
		HttpParams httpParameters = new BasicHttpParams();
		int timeoutConnection = 40000;
		HttpConnectionParams.setConnectionTimeout(httpParameters,
				timeoutConnection);
		int timeoutSocket = 40000;
		HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
		HttpClient client = new DefaultHttpClient(httpParameters);
		HttpResponse response = client.execute(request);
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			Util.print("服务器请求成功");
			InputStream is=response.getEntity().getContent();
			return is;
		}
		Util.print("服务器请求失败");
		return null;
	}
	

	/**
	 * POST
	 * 
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public static InputStream POSTJson(String url, String json)
			throws Exception {
		HttpPost request = new HttpPost(url);
		HttpEntity entity = new StringEntity(json,"UTF-8");
		request.setEntity(entity);
		request.addHeader("Content-Type", "application/json;charset=UTF-8");
		HttpParams httpParameters = new BasicHttpParams();
		int timeoutConnection = 5000;
		HttpConnectionParams.setConnectionTimeout(httpParameters,
				timeoutConnection);
		int timeoutSocket = 5000; 
		HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
		HttpClient client = new DefaultHttpClient(httpParameters);
		HttpResponse response = client.execute(request);
		System.out.println("POST:  "+response.getStatusLine().getStatusCode());
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			Util.print("服务器请求成功");
			return response.getEntity().getContent();
		}
		Util.print("服务器请求失败");
		return null;
	}

	/**
	 * GET
	 * 
	 * @param url
	 * @param map
	 * @return
	 * @throws Exception
	 */
	public static InputStream GET(String url, HashMap<String, String> map)
			throws Exception {
		String request = url + "?";
		StringBuffer sb = new StringBuffer();
		sb.append(request);
		for (Map.Entry<String, String> entry : map.entrySet()) {
			sb.append(entry.getKey() + "=" + entry.getValue() + "&");
		}
		String pageUrl = sb.toString().substring(0, sb.toString().length() - 1);
		URL requestUrl = new URL(pageUrl);
		HttpURLConnection urlConnection = (HttpURLConnection) requestUrl
				.openConnection();
		urlConnection.setRequestMethod("GET");
		urlConnection.setConnectTimeout(5 * 1000);
		if (urlConnection.getResponseCode() == 200) {
			Util.print("服务器请求成功");
			return urlConnection.getInputStream();
		}
		Util.print("服务器请求失败");
		return null;
	}

	/**
	 * GET
	 * 
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public static InputStream GET(String url) throws Exception {
		URL requestUrl = new URL(url);
		HttpURLConnection urlConnection = (HttpURLConnection) requestUrl
				.openConnection();
		urlConnection.setRequestMethod("GET");
		urlConnection.setConnectTimeout(5 * 1000);
		if (urlConnection.getResponseCode() == 200) {
			Util.print("服务器请求成功");
			return urlConnection.getInputStream();
		}
		Util.print("服务器请求失败");
		return null;
	}

	/**
	 * 
	 * @param inputStream
	 * @return 返回 byte[]
	 * @throws Exception
	 */
	public static byte[] read(InputStream inputStream) throws Exception {
		ByteArrayOutputStream arrayBuffer = new ByteArrayOutputStream();
		byte[] b = new byte[1024];
		int len = -1;
		while ((len = inputStream.read(b)) != -1) {
			arrayBuffer.write(b, 0, len);
		}
		byte[] bytes=arrayBuffer.toByteArray();
		inputStream.close();
		arrayBuffer.close();
		return bytes;
	}

	/**
	 * 读取流数据
	 * 
	 * @param inputStream
	 * @return ByteArrayOutputStream
	 * @throws Exception
	 */
	public static ByteArrayOutputStream readDate(InputStream inputStream)
			throws Exception {
		ByteArrayOutputStream arrayBuffer = new ByteArrayOutputStream();
		byte[] b = new byte[1024];
		int len = -1;
		while ((len = inputStream.read(b)) != -1) {
			arrayBuffer.write(b, 0, len);
		}
		inputStream.close();
		arrayBuffer.close();
		return arrayBuffer;
	}

	/**
	 * Bytes2Drawable
	 * 
	 * @param b
	 * @return
	 */
	public static Drawable Bytes2Drawable(byte[] b) {
		try {
			Bitmap bitmap = null;
			if (b.length != 0) {
				bitmap = BitmapFactory.decodeByteArray(b, 0, b.length);
				return new BitmapDrawable(bitmap);
			} else {
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * drawableToBitmap
	 * 
	 * @param drawable
	 * @return
	 */
	public static Bitmap drawableToBitmap(Drawable drawable) {
		Bitmap bitmap = null;
		if (drawable != null) {
			try {
				bitmap = Bitmap
						.createBitmap(
								drawable.getIntrinsicWidth(),
								drawable.getIntrinsicHeight(),
								drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
										: Bitmap.Config.RGB_565);
				Canvas canvas = new Canvas(bitmap);
				canvas.setBitmap(bitmap);
				drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable
						.getIntrinsicHeight());
				drawable.draw(canvas);
				return bitmap;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		} else {
			return null;
		}

	}

	/**
	 * Bitmap2Bytes
	 * 
	 * @param bm
	 * @return
	 */
	public static byte[] bitmap2Bytes(Bitmap bm) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
		return baos.toByteArray();
	}

	/**
	 * h获取网络图片
	 * 
	 * @param imgUrl
	 * @return
	 * @throws Exception
	 */
	public static Bitmap getImages(String imgUrl) throws Exception {
		URL url = new URL(imgUrl);
		HttpURLConnection urlConnection = (HttpURLConnection) url
				.openConnection();
		urlConnection.setRequestMethod("GET");
		urlConnection.setConnectTimeout(60 * 1000);
		Bitmap bitmap = null;
		if (urlConnection.getResponseCode() == 200) {
			InputStream inputStream = urlConnection.getInputStream();
			BitmapFactory.Options opt = new BitmapFactory.Options();
			opt.inPreferredConfig = Bitmap.Config.RGB_565;
			opt.inPurgeable = true;
			opt.inInputShareable = true;
			bitmap = BitmapFactory.decodeStream(inputStream, null, opt);
			inputStream.close();
			return bitmap;
			// return read(inputStream);
		}
		return bitmap;
	}

	/**
	 * 获取内容 get方式获取
	 * 
	 * @param pageUrl
	 * @param encoding
	 * @return
	 * @throws Exception
	 */
	public static String getContent(String pageUrl, String encoding)
			throws Exception {
		URL url = new URL(pageUrl);
		HttpURLConnection urlConnection = (HttpURLConnection) url
				.openConnection();
		urlConnection.setRequestMethod("GET");
		urlConnection.setConnectTimeout(6 * 1000);
		if (urlConnection.getResponseCode() == 200) {
			InputStream inputStream = urlConnection.getInputStream();
			byte[] data = read(inputStream);
			return new String(data, encoding);
		}
		return null;
	}

	public interface ContentCallback {
		public void contentLoaded(InputStream inputStream);
	}

	/**
	 * URL转换成IP
	 * 
	 * @param url
	 * @return
	 * @throws UnknownHostException
	 * @throws Exception
	 */
	public static String urlToIp(String url) throws UnknownHostException {
		String urlAdd = "";
		String httptop = url.substring(0, 7);
		if (httptop.equalsIgnoreCase("http://")) {
			urlAdd = url;
		} else {
			urlAdd = "http://" + url;
		}
		String newurl = "";
		Pattern p = Pattern.compile(
				"[^//]*?\\.(com|cn|net|org|biz|info|cc|tv)",
				Pattern.CASE_INSENSITIVE);
		try {
			Matcher matcher = p.matcher(urlAdd);
			if (matcher.find()) {
				String ip = InetAddress.getByName(matcher.group())
						.getHostAddress();
				newurl = urlAdd.replace(matcher.group(), ip);
			} else {
				newurl = urlAdd;
			}
		} catch (UnknownHostException e) {
			try {
				Matcher matcher = p.matcher(urlAdd);
				if (matcher.find()) {
					String ip = InetAddress.getByName(matcher.group())
							.getHostAddress();
					newurl = urlAdd.replace(matcher.group(), ip);
				} else {
					newurl = urlAdd;
				}
			} catch (UnknownHostException e1) {
				Matcher matcher = p.matcher(urlAdd);
				if (matcher.find()) {
					String ip = InetAddress.getByName(matcher.group())
							.getHostAddress();
					newurl = urlAdd.replace(matcher.group(), ip);
				} else {
					newurl = urlAdd;
				}
			}
		}
		return newurl;

	}
	public static InputStream upload_image(List<TaskManage> list,String userName) {
		String actionUrl = Protocol.getURL
				+ Protocol.getUpload.replaceAll("_", "/");
		HttpURLConnection connection = null;
		DataOutputStream outputStream = null;
		StringBuffer sTaskId = new StringBuffer();
		StringBuffer sStepId = new StringBuffer();
		StringBuffer sProjectId = new StringBuffer();
		for (int j = 0; j < list.size(); j++) {
			if (j == (list.size() - 1)) {
				sTaskId.append(list.get(j).getTaskId());
				sProjectId.append(list.get(j).getProjectId());
				sStepId.append(list.get(j).getStepId());
			} else {
				sTaskId.append(list.get(j).getTaskId() + ",");
				sProjectId.append(list.get(j).getProjectId()+ ",");
				sStepId.append(list.get(j).getStepId() + ",");
			}
		}
		StringBuffer params = new StringBuffer();
		params.append("login_name=").append(userName);
		params.append("&plan_id=").append(list.get(0).getPlanId());
		params.append("&plan_job_id_list=").append(sTaskId);
		params.append("&plan_project_code_list=").append(sProjectId);
		params.append("&step_id_list=").append(sStepId);
		String urlServer = actionUrl + "?" + params;
		String lineEnd = "\r\n";
		String twoHyphens = "--";
		// String boundary = "*****";
		// 定义数据分隔线
		String BOUNDARY = "------------------------7dc2fd5c0894";
		Util.print("urlServer:  "+urlServer);
		try {
			URL url = new URL(urlServer);
			connection = (HttpURLConnection) url.openConnection();

			connection.setDoInput(true);
			connection.setDoOutput(true);
			connection.setUseCaches(false);

			connection.setRequestMethod("POST");
			connection.setRequestProperty("Connection", "Keep-Alive");
			connection.setRequestProperty("Content-Type",
					"multipart/form-data;boundary=" + BOUNDARY);
			outputStream = new DataOutputStream(connection.getOutputStream());
			double progress=0;
			for (int i = 0; i < list.size(); i++) {
				StringBuilder sb = new StringBuilder();
				sb.append(twoHyphens + BOUNDARY + lineEnd);
				sb.append("Content-Disposition: form-data; name=\"files\";filename=\""
						+ list.get(i).getId() + ".jpg\"" + lineEnd);
				sb.append(lineEnd);
				outputStream.write(sb.toString().getBytes());
				progress+=1.0;
				netProgress.progress((int) progress);
				System.out.println("位置一  ： "+progress);
				byte[] bytes=list.get(i).getImages();
				ByteArrayInputStream byteInputStream=new ByteArrayInputStream(bytes);
				byte[] buf=new byte[1024];
				while(byteInputStream.read(buf, 0, buf.length)!=-1){
					System.out.println(bytes.length);
					outputStream.write(buf);
					progress+=((100.0-list.size()*2)/list.size())/(bytes.length/1024);
					netProgress.progress((int) progress);
					System.out.println("位置er  ： "+progress);
				}
				outputStream.write("\r\n".getBytes());
				progress+=1;
				netProgress.progress((int) progress);
				System.out.println("位置san  ： "+progress);
			}
			outputStream.writeBytes(lineEnd);
			outputStream.writeBytes(twoHyphens + BOUNDARY + twoHyphens
					+ lineEnd);
			int responseCode = connection.getResponseCode();
			connection.setConnectTimeout(6 * 1000);
			if (responseCode == HttpURLConnection.HTTP_OK) {
				InputStream is = connection.getInputStream();
				Util.print("上传成功");
				return is;
			} else {
				Util.print("请求服务器失败:  " + responseCode);
			}

		} catch (Exception ex) {
			ex.printStackTrace();
		}finally{
			/* 关闭DataOutputStream */
			try {
				outputStream.flush();
				outputStream.close();
//		/		if(connection!=null) connection.disconnect();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}
	public static void setNetProgress(NetProgress netProgress){
		NetTool.netProgress=netProgress;
	}
	public interface NetProgress{
		public void progress(int progress);
	}
}
